package com.mjt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.mjt.admin.model.RespDataBean;
import com.mjt.admin.pojo.User;
import com.mjt.admin.mapper.UserMapper;
import com.mjt.admin.pojo.UserRole;
import com.mjt.admin.query.UserQuery;
import com.mjt.admin.service.IUserRoleService;
import com.mjt.admin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjt.admin.utils.AssertUtil;
import com.mjt.admin.utils.StringUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 莫某人
 * @since 2021-10-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder encoder;

    @Resource
    private IUserRoleService userRoleService;


   /**
     * @description 用户登录
     * @author 莫某人
     * @date 11:10 2021/10/27
     * @param  username
     * @param  password
     * @return User
     **/



    /**
     * @description 根据用户名查询用户信息
     * @author 莫某人
     * @date 11:14 2021/10/27
     * @param username
     * @return {@link }
     **/
    @Override
    public User findUserByUsername(String username) {
       return this.baseMapper.selectOne(new QueryWrapper<User>()
                .eq("is_del",0)
                .eq("user_name",username));
    }

    /**
     * @description
     * @author 莫某人
     * @date 11:36 2021/10/27
     * @param userName
     * @param newPassword
     * @param oldPassword
     * @param confirmPassword
     * @return {@link }
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserPassword(String userName, String oldPassword, String newPassword, String confirmPassword) {

        AssertUtil.isTrue(null==this.findUserByUsername(userName),"用户不存在或未登录");
        //判断密码是否为空
        AssertUtil.isTrue(StringUtil.isEmpty(oldPassword),"旧密码不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(newPassword),"新密码不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(confirmPassword),"确认密码不能为空！");
        //判断新旧密码是否相同

        AssertUtil.isTrue(newPassword.equals(oldPassword),"新旧密码不能相同");
        //判断新密码和确认密码是否一致

        AssertUtil.isTrue(!newPassword.equals(confirmPassword),"两次密码输入不一致");

        //查询用户信息
        User user = findUserByUsername(userName);

        //对比旧密码输入是否正确
        //AssertUtil.isTrue(!user.getPassword().equals(oldPassword),"旧密码不正确！");
        AssertUtil.isTrue(!encoder.matches(oldPassword,user.getPassword()),"旧密码不正确");
        //更新用户信息
        user.setPassword(encoder.encode(newPassword));
        //更新密码
        this.baseMapper.update(user,new QueryWrapper<User>().eq("user_name",userName));
    }

    /**
     * @description 修改用户信息
     * @author 莫某人
     * @date 14:29 2021/10/27
     * @param user
     * @return {@link }
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserInfo(User user) {
        AssertUtil.isTrue(StringUtil.isEmpty(user.getUsername()),"用户名不能为空!");
        User temp = this.findUserByUsername(user.getUsername());
        AssertUtil.isTrue(null !=temp && !(temp.getId().equals(user.getId())),"用户名已存在!");
        AssertUtil.isTrue(!(this.updateById(user)),"用户信息更新失败!");


    }

    /**
     * @description  查询用户列表
     * @author 莫某人
     * @date 14:08 2021/10/28
     * @param userQuery
     * @return map
     **/
    @Override
    public RespDataBean<User> userList(UserQuery userQuery) {
        IPage<User> page=new Page<User>(userQuery.getPage(),userQuery.getLimit());

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del",0);
        if (StringUtils.isNotBlank(userQuery.getUserName())){
            wrapper.like("user_name",userQuery.getUserName())
            .or().like("bz",userQuery.getUserName())
            .or().like("true_name",userQuery.getUserName())
            .or().like("remarks",userQuery.getUserName());
        }
        page=this.userMapper.selectPage(page,wrapper);
        RespDataBean<User> result = new RespDataBean<>(0, "查询成功", page.getRecords(), page.getTotal());

        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveUser(User user) {
        AssertUtil.isTrue(StringUtil.isEmpty(user.getUsername()),"用户名不能为空！");


        //查询用户名是否已经存在
        User userByUsername = findUserByUsername(user.getUsername());
        AssertUtil.isTrue(!Objects.isNull(userByUsername),"用户名已经存在！");

        AssertUtil.isTrue(StringUtil.isEmpty(user.getBz()),"备注名不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(user.getRemarks()),"备注不能为空！");
        //用户密码默认为123456
        user.setPassword(encoder.encode("123456"));
        AssertUtil.isTrue(!save(user),"用户添加失败");
        //添加用户角色信息
        List<UserRole> userRoles = new ArrayList<>();
        Integer[] roleIds = user.getRoleIds();
        for (Integer roleId : roleIds) {
            //遍历保存选中的角色id
            userRoles.add(new UserRole(roleId,user.getId()));
        }
        AssertUtil.isTrue(!userRoleService.saveBatch(userRoles),"角色添加失败");



    }


    /**
     * @description 修改用户信息
     * @author 莫某人
     * @date 16:21 2021/10/28
     * @param user
     * @return {@link }
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUser(User user) {

        AssertUtil.isTrue(StringUtil.isEmpty(user.getUsername()),"用户名不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(user.getBz()),"备注名不能为空！");
        AssertUtil.isTrue(StringUtil.isEmpty(user.getRemarks()),"备注不能为空！");


        AssertUtil.isTrue(!updateById(user),"用户更新失败");
        //更新角色信息

        if (user.getRoleIds().length==0||user.getRoleIds()==null){
            //判断如果角色被清空
           userRoleService.remove(new QueryWrapper<UserRole>()
            .eq("user_id",user.getId())
            );
        }else {
            //如果角色不为空
            //清空角色信息
            userRoleService.remove(new QueryWrapper<UserRole>()
                    .eq("user_id",user.getId())
            );

            //获取得到的角色id
            Integer[] roleIds = user.getRoleIds();
            List<UserRole> userRoles = new ArrayList<>();
            for (Integer roleId : roleIds) {
                //遍历保存选中的角色id
                userRoles.add(new UserRole(roleId,user.getId()));
            }
            AssertUtil.isTrue(!userRoleService.saveBatch(userRoles),"角色添加失败");

        }










    }

    /**
     * @description 删除用户
     * @author 莫某人
     * @date 16:15 2021/10/28
     * @param ids
     * @return {@link }
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteUsers(Integer[] ids) {
        AssertUtil.isTrue(ids==null||ids.length==0,"请选择待删除的记录id");
        ArrayList<User> userTemp = new ArrayList<>();
        for (Integer id : ids) {
            User user = this.getById(id);
            user.setIsDel(1);
            userTemp.add(user);
            //删除用户角色信息
            userRoleService.remove(new QueryWrapper<UserRole>()
                    .eq("user_id",id));

        }
        AssertUtil.isTrue(!this.updateBatchById(userTemp),"删除失败");

        //删除用户角色信息



    }
}
